const { getUserId, PermissionError, ExistsNameError } = require('../../utils')

const isExistsGroupWithName = async ({ ctx, id, name }) => {
  const existsGroup = await ctx.db.exists.Group({ id, name })
  // 判断是否存在, 基于程序限制 name 值唯一
  if (existsGroup) {
    throw new ExistsNameError()
  }
}

const isGroupOwner = async ({ ctx, id, userId, nameNot }) => {
  let where
  if (nameNot) {
    where = {
      OR: [{
        id,
        owner: {
          id: userId
        }
      }, {
        id,
        name_not: nameNot
      }]
    }
  } else {
    where = {
      id,
      owner: {
        id: userId
      }
    }
  }
  const groups = await ctx.db.query.groups({ where })
  // console.log(group)
  if (!groups || groups.length < 0) {
    throw new PermissionError()
  }
}

const group = {
  async createGroup (parent, { name }, ctx, info) {
    await isExistsGroupWithName({ ctx, name })
    const userId = getUserId(ctx)
    return ctx.db.mutation.createGroup(
      {
        data: {
          name,
          owner: {
            connect: { id: userId }
          }
        }
      },
      info
    )
  },
  async deleteGroup (parent, { id }, ctx, info) {
    // 判断 id 是否能删除
    // await isExistsGroupWithName({ ctx, id, name: '已关注' })
    const userId = getUserId(ctx)
    await isGroupOwner({ ctx, id, userId, nameNot: '已关注' })
    return ctx.db.mutation.deleteGroup(
      {
        where: {
          id
        }
      },
      info
    )
  },
  async updateGroup (parent, { id, name, usersId, removeUsersId }, ctx, info) {
    // 判断 id 是否能修改
    /* if (name) {
      await isExistsGroupWithName({ ctx, name })
    } */
    const userId = getUserId(ctx)
    await isGroupOwner({ ctx, id, userId, nameNot: name })
    const data = {}
    if (name) {
      data.name = name
    }
    if (usersId) {
      data.users = {
        connect: [{
          id: usersId
        }]
      }
    }
    if (removeUsersId) {
      data.users = {
        disconnect: [{
          id: removeUsersId
        }]
      }
    }
    return ctx.db.mutation.updateGroup(
      {
        where: {
          id
        },
        data
      },
      info
    )
  }
}

module.exports = { group }
